package com.smallkingson.ylib.view.drawable;

import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.LightingColorFilter;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import com.smallkingson.ylib.core.Yr;

/**
 * The stateful LayerDrawable used by this button.
 */
public class SelectorDrawable extends LayerDrawable {

  // The color filter to apply when the button is pressed
  protected ColorFilter _pressedFilter = new LightingColorFilter(Color.LTGRAY, 1);
  // Alpha value when the button is disabled
  protected int _disabledAlpha = 100;
  // Alpha value when the button is enabled
  protected int _fullAlpha = 255;
  private LightingColorFilter _focusedColorFilter = new LightingColorFilter(0x5548b4e7, 0);

  public SelectorDrawable(Drawable d) {
    super(new Drawable[] { d });
  }

  @Override protected boolean onStateChange(int[] states) {
    boolean enabled = false;
    boolean pressed = false;
    boolean focused = false;

    for (int state : states) {
      if (state == android.R.attr.state_enabled) {
        enabled = true;
      } else if (state == android.R.attr.state_pressed) {
        pressed = true;
      } else if (state == android.R.attr.state_focused) {
        focused = true;
      }
    }

    mutate();
    Drawable drawable = getDrawable(0);

    int numberOfLayers = getNumberOfLayers();
    Yr.d(numberOfLayers);
    //if (enabled && pressed) {
    //  if (drawable instanceof BitmapDrawable) {
    //    setColorFilter(_pressedFilter);
    //  } else {
    //    drawable.mutate().setAlpha((int) (255 * 0.8));
    //  }
    //} else if (!enabled) {
    //  setColorFilter(null);
    //  setAlpha(_disabledAlpha);
    //} else {
    //  setColorFilter(null);
    //  setAlpha(_fullAlpha);
    //}

    if (enabled) {
      if (pressed || focused) {
        if (pressed) {
          if (drawable instanceof BitmapDrawable) {
            setColorFilter(_pressedFilter);
          } else {
            drawable.mutate().setAlpha((int) (255 * 0.8));
          }
        }
        if (focused) {
          if (drawable instanceof BitmapDrawable) {
            //setColorFilter(_pressedFilter);
            drawable.mutate().setColorFilter(_focusedColorFilter);
          } else {
            //drawable.mutate().setAlpha((int) (255 * 0.8));
            drawable.mutate().setColorFilter(_focusedColorFilter);
          }
        }
        if (!pressed) {
          drawable.mutate().setAlpha(_fullAlpha);
          drawable.mutate().setColorFilter(_focusedColorFilter);
        }
      } else {
        setColorFilter(null);
        setAlpha(_fullAlpha);
      }
    } else {
      setColorFilter(null);
      setAlpha(_disabledAlpha);
    }

    invalidateSelf();

    return super.onStateChange(states);
  }

  @Override public boolean isStateful() {
    return true;
  }
}
